package com.kaixinff.kaixin001.common;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import com.kaixinff.net.HttpClient;
import com.kaixinff.net.HttpResponse;
import com.kaixinff.net.NameValuePair;

public class KaiXin001Client extends HttpClient {
	public static final String LOGIN_URL = "http://login.kaixin001.com/";

	public KaiXin001Client() {
		super();
	}
	
	public HttpResponse login(String username, String pwd)
			throws IOException, JSONException {
		String cont = doGet(LOGIN_URL, null).getContent();
		Pattern p = Pattern.compile("var loginMgr = new EnLogin[(]'(.+?)'");
		Matcher m = p.matcher(cont);
		if (!m.find()) {
			return null;
		}
		String encypt = m.group(1);
		String rpasswd = Encrypt.enp(pwd, encypt);
		cont = this.doPost("http://login.kaixin001.com/login/login_api.php",
				LOGIN_URL, new NameValuePair[] { new NameValuePair("ver", "1"),
						new NameValuePair("email", username),
						new NameValuePair("rpasswd", rpasswd),
						new NameValuePair("encypt", encypt),
						new NameValuePair("url", "/home/"),
						new NameValuePair("invisible_mode", "0") }).getContent();

		JSONObject jobj = new JSONObject(cont);
		String url = "http://" + HttpClient.getHost(LOGIN_URL)
				+ jobj.getString("loc");

		return doGet(url, LOGIN_URL, null);
	}
}
